package com.lzm.easyexcel.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author liuzemin
 * @date 2023/8/10 0010 22:06
 * @description
 */
@Slf4j
public class EasyExcelListener implements ReadListener {

    List<Object> data = new ArrayList<>();

    public List<Object> getData() {
        return data;
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        log.info("解析出错："+exception.getMessage());

        int row=0,column=0;
        String cellMsg = null;
        if (exception instanceof ExcelDataConvertException){
            ExcelDataConvertException convertException=(ExcelDataConvertException) exception;

            row=convertException.getRowIndex() + 1;
            column=convertException.getColumnIndex() + 1;
            //通过celldatatype的枚举值,用来判断CellData的数据类型
            CellData<?> cellData = convertException.getCellData();
            CellDataTypeEnum type = cellData.getType();
            if (type.equals(CellDataTypeEnum.NUMBER)) {
                cellMsg = cellData.getNumberValue().toString();
            } else if (type.equals(CellDataTypeEnum.STRING)) {
                cellMsg = cellData.getStringValue();
            } else if (type.equals(CellDataTypeEnum.BOOLEAN)) {
                cellMsg = cellData.getBooleanValue().toString();
            }
            log.error("解析出错：{}行 {}列 值{}",row,column,cellMsg);
            throw new RuntimeException("数据解析出错："+row+"行 "+column+"列 值为"+ cellMsg +"，停止运行");
        }
        throw new RuntimeException(exception);
    }

    @Override
    public void invoke(Object o, AnalysisContext analysisContext) {
        Integer rowIndex = analysisContext.readRowHolder().getRowIndex();
        try {
            Method method = o.getClass().getMethod("setRowIndex", Integer.class);
            method.invoke(o, rowIndex);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        data.add(o);
    }

    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        ReadListener.super.extra(extra, context);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    @Override
    public boolean hasNext(AnalysisContext context) {
        return ReadListener.super.hasNext(context);
    }
}
